package com.cqeec.myblog.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.cqeec.myblog.model.Photo;
import com.cqeec.myblog.util.DbUtil;

public class PhotoDaoImpl implements PhotoDao {

	@Override
	public void save(Photo photo) throws ClassNotFoundException, SQLException {
		Connection conn = DbUtil.getDbConnection();
		PreparedStatement ps = conn.prepareStatement("INSERT INTO Photo VALUES(?,?,?,?)");
		ps.setString(1, photo.getId());
		ps.setString(2, photo.getAlbum());
		ps.setString(3, photo.getName());
		ps.setDate(4, new java.sql.Date(photo.getUploadTime().getTime()));
		ps.executeUpdate();
		ps.close();
	}

	@Override
	public List<Photo> findByAlbum(String albumId) throws ClassNotFoundException, SQLException {
		List<Photo> list = new ArrayList<Photo>();
		Connection conn = DbUtil.getDbConnection();
		PreparedStatement ps = conn.prepareStatement(
				"SELECT Photo.id,photo.name,photo.file,photo.uploadTime,CONCAT(album.blogger,'/',photo.album) album FROM Photo INNER JOIN Album ON photo.album=Album.id WHERE photo.album=?");
		ps.setString(1, albumId);
		ResultSet rs = ps.executeQuery();
		Photo photo;
		while (rs.next()) {
			photo = new Photo();
			photo.setId(rs.getString("id"));
			photo.setAlbum(rs.getString("album"));
			photo.setName(rs.getString("name"));
			photo.setFile(rs.getString("file"));
			photo.setUploadTime(rs.getDate("uploadTime"));
			list.add(photo);
		}
		rs.close();
		ps.close();
		return list;
	}

}
